import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;

public class SortProperties {

	public static void main(String[] args) throws IORuntimeException, IOException {
		File file = new File(
		      "F:\\coding-workspace\\plugins-workspace\\repo-filerep\\src\\main\\resources\\org\\pentaho\\di\\ui\\repository\\messages\\messages_zh_CN.properties");
		List<String> lines = FileUtil.readLines(file, "UTF-8");

		CollectionUtil.sort(lines, (o1, o2) -> {
			return o1.compareTo(o2);
		});

		List<String> newLines = Lists.newArrayList();
		for (String line : lines) {
			if(StrUtil.isBlank(line.trim()) || line.startsWith("#")) {
				continue;
			}
			newLines.add(unicodeToChina(line));
		}

		FileUtil.writeLines(newLines, file, "UTF-8");
	}

	public static String unicodeToChina(String str) {
		Charset set = Charset.forName("UTF-16");
		Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
		Matcher m = p.matcher(str);
		int start = 0;
		int start2 = 0;
		StringBuffer sb = new StringBuffer();
		while (m.find(start)) {
			start2 = m.start();
			if (start2 > start) {
				String seg = str.substring(start, start2);
				sb.append(seg);
			}
			String code = m.group(1);
			int i = Integer.valueOf(code, 16);
			byte[] bb = new byte[4];
			bb[0] = (byte) ((i >> 8) & 0xFF);
			bb[1] = (byte) (i & 0xFF);
			ByteBuffer b = ByteBuffer.wrap(bb);
			sb.append(String.valueOf(set.decode(b)).trim());
			start = m.end();
		}
		start2 = str.length();
		if (start2 > start) {
			String seg = str.substring(start, start2);
			sb.append(seg);
		}
		return sb.toString();
	}

}
